package cn.codecang.mall.common.advice;

import cn.codecang.mall.common.consts.ErrorCode;
import cn.codecang.mall.common.exception.CustomException;
import cn.codecang.mall.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.context.support.DefaultMessageSourceResolvable;

import java.util.stream.Collectors;

/**
 * BasicExceptionHandler 对系统报错进行统一处理
 *
 * @author xiaoluo
 * @date 2023/6/3 22:11
 */
@Slf4j
@ControllerAdvice
public class BasicExceptionHandler {
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public @NotNull Result<Object> errorHandler(@NotNull Exception exception) {
        return Result.build(500, exception.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = ArithmeticException.class)
    public @NotNull Result<Object> errorHandler(@NotNull ArithmeticException exception) {
        return Result.build(500, "运算异常");
    }

    @ResponseBody
    @ExceptionHandler(value = CustomException.class)
    public Result<Object> errorHandler(@NotNull CustomException exception) {
        return Result.error(exception.getCode());
    }


    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public Result<Object> errorHandler(@NotNull BindException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        //获取所有校验异常信息进行拼接返回
        String message = bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return Result.build(ErrorCode.INVALID_PARAMETER.getCode(), message);
    }
}
